package cn.mesmile.flink.monitor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Date;

/**
 * @author zb
 * @date 2021/8/29 0:18
 * @Description
 *  ProcessWindowFunction 方法说明
 *    一次性迭代整个窗口里的所有元素，通过Context，可以获取到事件、窗口和状态信息
 *    可以和ReduceFunction, AggregateFunction 来做增量计算
 *    在Agg方法做第2个参数 ，windowFunction 会把每个 key 的窗口聚合后的结果带上 上下文信息进行输出
 *    之前ProcessWindowFunction是获取整个窗口的全部元素，在agg方法里面是获取聚合后的结果，一个元素
 *    aggregate( AggregateFunction<T, ACC, V> aggFunction,
 *    ProcessWindowFunction<V, R, K, W> windowFunction )
 */
public class FlinkMonitorApp {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        environment.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        environment.setParallelism(1);

        //java,2022-11-11 09-10-10,15
        DataStream<AccessLogDO> ds =  environment.addSource(new AccessLogSource());
        // 过滤
        SingleOutputStreamOperator<AccessLogDO> filterDS = ds.filter(new FilterFunction<AccessLogDO>() {
            @Override
            public boolean filter(AccessLogDO value) throws Exception {
                return StrUtil.isNotBlank(value.getUrl());
            }
        });
        //指定watermark
        SingleOutputStreamOperator<AccessLogDO> watermarkDS = filterDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                //指定允许乱序延迟的最大时间 3
                .<AccessLogDO>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                //指定POJO事件时间列，毫秒
                .withTimestampAssigner(
                        (event, timestamp) -> event.getCreateTime().getTime()
                )
        );
        //最后的兜底数据
        OutputTag<AccessLogDO> lateData = new OutputTag<AccessLogDO>("lateDataLog"){};

        //分组
        KeyedStream<AccessLogDO, String> keyedStream = watermarkDS.keyBy(new KeySelector<AccessLogDO, String>() {
            @Override
            public String getKey(AccessLogDO value) throws Exception {
                return value.getUrl();
            }
        });
        WindowedStream<AccessLogDO, String, TimeWindow> accessLogDOStringTimeWindowWindowedStream = keyedStream
                //开窗
                .window(SlidingEventTimeWindows.of(Time.seconds(60), Time.seconds(5)))
                //允许1分钟延迟
                .allowedLateness(Time.minutes(1))
                // 最后迟到的数据
                .sideOutputLateData(lateData);

        SingleOutputStreamOperator<ResultCount> aggregate = accessLogDOStringTimeWindowWindowedStream.aggregate(new AggregateFunction<AccessLogDO, Long, Long>() {
            @Override
            public Long createAccumulator() {
                return 0L;
            }

            @Override
            public Long add(AccessLogDO value, Long accumulator) {
                return accumulator + 1;
            }

            @Override
            public Long getResult(Long accumulator) {
                return accumulator;
            }

            @Override
            public Long merge(Long a, Long b) {
                return a + b;
            }
        }, new ProcessWindowFunction<Long, ResultCount, String, TimeWindow>() {
            @Override
            public void process(String value, Context context, Iterable<Long> elements, Collector<ResultCount> out) throws Exception {
                ResultCount resultCount = new ResultCount();
                resultCount.setUrl(value);
                resultCount.setType("每5秒统计近1分接口PV");
                resultCount.setStartTime(DateUtil.formatDateTime(new Date(context.window().getStart())));
                resultCount.setEndTime(DateUtil.formatDateTime(new Date(context.window().getEnd())));
                long total = elements.iterator().next();
                resultCount.setCount(total);
                out.collect(resultCount);
            }
        });

        aggregate.print("一分钟访问量:");

        environment.execute();
    }
}
